package com.ailesson.common.util;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtUtil {

    //token字符串有效时间
    private static long tokenExpiration = 24*60*60*1000;
    //加密编码秘钥
    private static String tokenSignKey = "AFS$TE#%B$%##FT@RWRcc";

    public static String TOKEN_NAME = "X-Token";

    /**
     *  根据userid  和  username 生成token字符串
     */
    public static String createToken(Long userId, String userName) {
        return Jwts.builder()
                .setSubject("AILesson")
                .setExpiration(new Date(System.currentTimeMillis()+tokenExpiration))
                .claim("userId",userId)
                .claim("userName",userName)
                .signWith(SignatureAlgorithm.ES256,tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();

    }

    /**
     *从token字符串获取userId
     * @param token
     * @return
     */
    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Long userId = (Long)claimsJws.getBody().get("userId");
        return userId;
    }
    /**
     *  从token字符串获取getUserName
     */
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)) {
            return "";
        }
        Jws<Claims> claimsJws
                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("userName");
    }
}
